#include <string.h>
#include <stdlib.h>

#include "tick.h"
#include "timer.h"
#include "hardware.h"
#include "BatteryMonitorADC.h"
#include "SensorChannels.h"


#undef TRACE_LEVEL
#undef TRACE_TITLE
#undef TRACE_TITLE
#define TRACE_LEVEL TRACE_LEVEL_DEBUG
#define TRACE_NAME  TRACE_NAME_DISABLE
#define TRACE_TITLE "BETTRY"
#include "trace.h"


static volatile int ADC2ConvertDone = FALSE;

void BetteryMonitorADCInit() {
	ADC_InitTypeDef ADC_InitStructure;
	
	ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
	// ADC_InitStructure.ADC_ScanConvMode = ENABLE;
	ADC_InitStructure.ADC_ScanConvMode = DISABLE;
	// ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;
	ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
	ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
	ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
	// ADC_InitStructure.ADC_NbrOfChannel = 3;
	// ADC_InitStructure.ADC_NbrOfChannel = 6;
	ADC_Init(ADC2, &ADC_InitStructure);
	
	/* ADC2 regular channels configuration */  
	ADC_RegularChannelConfig(ADC2, BATTERY_MONITOR_ADC_CH, 1, ADC_SampleTime_28Cycles5);
	
	/* Enable ADC2 DMA */
	// ADC_DMACmd(ADC2, ENABLE);
	
	/* Enable ADC2 */
	ADC_Cmd(ADC2, ENABLE);

	/* Enable ADC2 reset calibration register */   
	ADC_ResetCalibration(ADC2);
	/* Check the end of ADC2 reset calibration register */
	while(ADC_GetResetCalibrationStatus(ADC2));

	/* Start ADC2 calibration */
	ADC_StartCalibration(ADC2);
	/* Check the end of ADC2 calibration */
	while(ADC_GetCalibrationStatus(ADC2));
	
	// ADC Interrupt Mode Config
	ADC_ITConfig(ADC2, ADC_IT_EOC, ENABLE);
	
	// ADC_SoftwareStartConvCmd(ADC2, ENABLE);
}

void BetteryMonitorADCDeInit() {
	ADC_ITConfig(ADC2, ADC_IT_EOC, DISABLE);
	ADC_Cmd(ADC2, DISABLE);
}

void ReadBerrtyADCValue(uint16_t *buf) {
	ADC2ConvertDone = FALSE;
	
	ADC_SoftwareStartConvCmd(ADC2, ENABLE);
	while(!ADC2ConvertDone);
	
	*buf = ADC_GetConversionValue(ADC2);
}

void ADC2EndOfConvertInterruptHandler() {
	ADC2ConvertDone = TRUE;
}


int BetteryMonitorADCMain() {
	uint16_t value;
	
	BetteryMonitorADCInit();
	while(1) {
		ReadBerrtyADCValue(&value);
		TRACE_DEBUG("Bettry ADC Value: %d, Volt: %0.1f", value, (float)value * 6.6 / 4096.0);
		delay_ms(1000);
	}
}

